package cn.com.freelibra.forum.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.alibaba.fastjson.JSONObject;

import cn.com.freelibra.forum.po.EmailCatcha;
import cn.com.freelibra.forum.po.User;
import cn.com.freelibra.forum.service.EmailCatchaService;
import cn.com.freelibra.forum.service.UserService;
import cn.com.freelibra.forum.util.StringUtil;
import cn.com.freelibra.forum.util.email.EmailUtil;
import cn.com.freelibra.forum.web.view.AjaxObject;

@Controller
@RequestMapping("/user")
public class UserController {

	@Value("${url}")
	String url;
	@Value("${sender}")
	String sender;
	@Value("${username}")
	String username;
	@Value("${password}")
	String password;
	@Value("${host}")
	String host;

	@Resource
	private UserService userService;

	@Resource
	private EmailCatchaService emailCatchaService;

	@RequestMapping("/checkUserName")
	public ModelAndView checkUserName(HttpServletRequest request) {
		String userName = request.getParameter("userName");
		List<User> users = this.userService.byName(userName);
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		if (users.size() > 0) {
			map.put("valid", false);
		} else {
			map.put("valid", true);
		}
		return new ModelAndView(new MappingJackson2JsonView(), map);
	}

	@RequestMapping("/checkEmail")
	public ModelAndView checkEmail(HttpServletRequest request) {
		String email = request.getParameter("email");
		List<User> users = this.userService.byEmail(email);
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		if (users.size() > 0) {
			map.put("valid", false);
		} else {
			map.put("valid", true);
		}
		return new ModelAndView(new MappingJackson2JsonView(), map);
	}

	@RequestMapping("/register")
	public String register(User user, HttpServletRequest request, RedirectAttributes attr) {
		// 对已存在邮箱账号的验证码进行清除
		emailCatchaService.deleteEmailCatcha(user.getUserName());
		// 发送邮件激活地址
		EmailUtil emailUtil = new EmailUtil();
		String emailcatch = emailUtil.SendEmail(user.getUserName(), user.getEmail(), host, url, sender, username,
				password);
		if (StringUtil.isNotEmpty(emailcatch)) {
			EmailCatcha emailCatcha = new EmailCatcha();
			emailCatcha.setCreateTime(new Date());
			emailCatcha.setCaptcha(emailcatch);
			emailCatcha.setUserName(user.getUserName());
			emailCatchaService.saveEmailCatcha(emailCatcha);
		}
		user.setDisabled(false);
		user.setCreateTime(new Date());
		user.setNickName(UUID.randomUUID().toString());
		attr.addFlashAttribute("user", user);
		if (this.userService.registerUser(user) > 0) {
			attr.addFlashAttribute("user", user);
			attr.addFlashAttribute("result", "0");
		} else {
			attr.addFlashAttribute("result", "1");
		}
		return "redirect:/user/registerResult";
	}

	@RequestMapping("/registerResult")
	public String registerSuccess() {
		return "/user/registerResult";
	}

	@RequestMapping("/activationUser")
	public String activationUser(HttpServletRequest request) {
		String userName = request.getParameter("userName");
		String emailcatch = request.getParameter("emailCaptcha");
		if (emailCatchaService.activationEmail(userName, emailcatch)) {
			User user = userService.byName(userName).get(0);
			request.getSession().setAttribute("user", user);
			return "redirect:/index";
		} else {
			return "redirect:/index";
		}
	}

/*	@RequestMapping("/login")
	@ResponseBody
	public AjaxObject login(String userName, String password, HttpServletRequest request) {
		AjaxObject result = new AjaxObject();
		if (userName == null || "".equals(userName.trim())) {
			result.setStatus(401);// 找不到用户
			result.setMsg("请输入账号！");// 提示内容
			result.setAction("alert");// 弹窗提示
			return result;
		}
		if (password == null || "".equals(password.trim())) {
			result.setStatus(402);// 找不到用户
			result.setMsg("请输入密码！");// 提示内容
			result.setAction("alert");// 弹窗提示
			return result;
		}
		User user = this.userService.byNameAndPassword(userName, password);
		if (user == null) {
			result.setStatus(404);// 找不到用户
			result.setMsg("用户或密码不正确！");// 提示内容
			result.setAction("alert");// 弹窗提示
			return result;
		} else {
			// 判断用户是否激活
			if (user.getDisabled().equals(true)) {
				request.getSession().setAttribute("user", user);
				result.setStatus(200);// 找不到用户
				String name = (user.getNickName() == null || "".equals(user.getNickName().trim())) ? user.getUserName()
						: user.getNickName();
				result.setMsg("【" + name + "】，欢迎您！");// 提示内容
				result.setAction("refresh");// 刷新当前页
				return result;
			} else {
				result.setStatus(500);// 找不到用户
				result.setMsg("请在邮件中点击链接激活账号！");// 提示内容
				result.setAction("alert");// 弹窗提示
				return result;
			}
		}
	}*/

	
    //用户登录
    @RequestMapping("/login")
    public String login(User user, HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getUserPassword());
        try{
            subject.login(token);//会跳到我们自定义的realm中
            request.getSession().setAttribute("user", user);
            return "/index";
        }catch(Exception e){
            e.printStackTrace();
            request.getSession().setAttribute("user", user);
            request.setAttribute("error", "用户名或密码错误！");
            return "login";
        }
    }

	
	@RequestMapping("/login2")
	@ResponseBody
	public AjaxObject login2(String userName, String password, HttpServletRequest request) {
		AjaxObject result = new AjaxObject();
		// 创建默认的httpClient实例.
				CloseableHttpClient httpclient = HttpClients.createDefault();
				// 创建httppost
				HttpPost httppost = new HttpPost("http://localhost/user/login");
				// 创建参数队列
				List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
				formparams.add(new BasicNameValuePair("userName", userName));
				formparams.add(new BasicNameValuePair("password", password));
				UrlEncodedFormEntity uefEntity;
				try {
					uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
					httppost.setEntity(uefEntity);
					System.out.println("executing request " + httppost.getURI());
					CloseableHttpResponse response = httpclient.execute(httppost);
					try {
						HttpEntity entity = response.getEntity();
						JSONObject jsons = JSONObject.parseObject(EntityUtils.toString(entity, "UTF-8"));
						result = (AjaxObject)JSONObject.toJavaObject(jsons,AjaxObject.class);
						System.out.println("=============s===="+result);
					} finally {
						response.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}  finally {
					// 关闭连接,释放资源
					try {
						httpclient.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

				request.getSession().setAttribute("user", result.getData());
				return result;
	}
	@RequestMapping("/loginout")
	public String loginout(HttpServletRequest request) {
		request.getSession().removeAttribute("user");
		return "redirect:/index";
	}

	@RequestMapping("/modify")
	public String userDetail(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		if (user != null) {
			// request.setAttribute("user",user);
			return "/user/modify";
		} else {
			return "redirect:/index";
		}
	}

	@RequestMapping("/view")
	public String otherDetail(HttpServletRequest request, Long id) {
		User user = userService.load(id);
		if (user != null) {
			request.setAttribute("user", user);
			return "/user/view";
		} else {
			return "redirect:/index";
		}
	}

	// POST
	@RequestMapping("/test")
	@ResponseBody
	public void test() {
		// 创建默认的httpClient实例.
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 创建httppost
		HttpPost httppost = new HttpPost("http://localhost/user/test");
		// 创建参数队列
		List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
		formparams.add(new BasicNameValuePair("name", "admin"));
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httppost.setEntity(uefEntity);
			System.out.println("executing request " + httppost.getURI());
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity entity = response.getEntity();
				JSONObject jsons = JSONObject.parseObject(EntityUtils.toString(entity, "UTF-8"));
				AjaxObject aj= (AjaxObject)JSONObject.toJavaObject(jsons,AjaxObject.class);
				System.out.println("================="+aj);
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 发送 get请求
	 */
	@RequestMapping("/test2")
	@ResponseBody
	public void get() {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			// 创建httpget.
			HttpGet httpget = new HttpGet("http://localhost/user/test?name=admin");
			System.out.println("executing request " + httpget.getURI());
			// 执行get请求.
			CloseableHttpResponse response = httpclient.execute(httpget);
			try {
				// 获取响应实体
				HttpEntity entity = response.getEntity();
				System.out.println("--------------------------------------");
				// 打印响应状态
				System.out.println(response.getStatusLine());
				if (entity != null) {
					// 打印响应内容长度
					System.out.println("Response content length: " + entity.getContentLength());
					// 打印响应内容
					System.out.println("Response content: " + EntityUtils.toString(entity));
				}
				System.out.println("------------------------------------");
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
